package torres.map.areaeffect;

import torres.entity.Entity;
import torres.fileIO.ClassContainer;
import torres.fileIO.BasicContainer;

/**
 * @author Torres
 * A special kind of AreaEffect that allows an Entity to Level Up if
 * it has sufficient experience.
 */
public class LevelUp implements AreaEffect {
	
	private int seconds;
	private long elapsed;
	private long lastUsed;
	
	/**
	 * Creates a new LevelUp AreaEffect with the default rate of 1 second.
	 */
	public LevelUp() {
		
		this.seconds = 1;
		this.elapsed = 0;
		this.lastUsed = 0;
	}
	
	
	/**
	 * Creates a new LevelUp AreaEffect with specified rate.
	 * @param seconds Rate of AreaEffect in seconds.
	 */
	public LevelUp(int seconds) {
		
		this.seconds = seconds;
		this.elapsed = 0;
		this.lastUsed = 0;
	}
	
	/* (non-Javadoc)
	 * @see torres.map.areaeffect.AreaEffect#applyEffect(torres.entity.Entity)
	 */
	public boolean applyEffect(Entity e) {
		
		if(elapsed >= ((long) 1000000000 * seconds)) {
			
			e.updateLevel();
			this.lastUsed = System.nanoTime();
			this.elapsed = 0;
			return true;
		}
		else {
			
			this.elapsed = System.nanoTime() - lastUsed;
			return false;
		}
	}
	
	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	public String toString() {
		
		return "Leveled up!";
	}

	/* (non-Javadoc)
	 * @see torres.fileIO.Saveable#save()
	 */
	@Override
	public ClassContainer save() {
		ClassContainer curClass = new ClassContainer("LevelUp");
		curClass.addProperty(new BasicContainer("seconds", this.seconds));
		curClass.addProperty(new BasicContainer("elapsed", this.elapsed));
		curClass.addProperty(new BasicContainer("lastUsed", this.lastUsed));
		
		return curClass;
	}

	/* (non-Javadoc)
	 * @see torres.fileIO.Saveable#load(torres.fileIO.ClassContainer)
	 */
	@Override
	public void load(ClassContainer classContainer) {
		BasicContainer secondsCont = (BasicContainer)classContainer.getProperty("seconds");
		seconds = Integer.parseInt((String)secondsCont.getValue());
		BasicContainer elapsedCont = (BasicContainer)classContainer.getProperty("elapsed");
		elapsed = Long.parseLong((String)elapsedCont.getValue());
		BasicContainer lastUsedCont = (BasicContainer)classContainer.getProperty("lastUsed");
		lastUsed = Long.parseLong((String)lastUsedCont.getValue());
		
	}
}
